/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CreateTorrentForm.java
 *
 * Created on Apr 9, 2011, 7:12:23 PM
 */

package bitetorrent.form;

import bitetorrent.Torrent;
import bitetorrent.helper.Request;
import bitetorrent.model.FileDownloader;
import bitetorrent.model.Global;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileFilter;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.Popup;

/**
 *
 * @author Robert Gunawan
 */
public class CreateTorrentForm extends javax.swing.JDialog {
    Torrent torrent;

    /** Creates new form CreateTorrentForm */
    public CreateTorrentForm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        // Determine the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width - w) / 2;
        int y = (dim.height - h) / 2;

        // Move the window
        this.setLocation(x, y);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        FileAsal = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        partisi = new javax.swing.JComboBox();
        CreateTorrent = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        URL = new javax.swing.JTextField();
        Rename = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        port = new javax.swing.JTextField();
        fileTujuan = new javax.swing.JTextField();
        GetName = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Create Torrent Form");

        jLabel6.setText("KB");

        jLabel5.setText("Ukuran Partisi");

        partisi.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "32", "64", "128", "256", "512", "1024", "2048", "4096" }));

        CreateTorrent.setText("Create Torrent");
        CreateTorrent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CreateTorrentActionPerformed(evt);
            }
        });

        jLabel8.setText("Nama File Asal");

        jLabel3.setText("URL");

        Rename.setText("Rename");
        Rename.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RenameActionPerformed(evt);
            }
        });

        jLabel4.setText("Port");

        jLabel7.setText("Nama File Torrent");

        GetName.setText("GetName");
        GetName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GetNameActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(URL, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(partisi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(fileTujuan, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Rename))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(FileAsal, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(GetName))
                    .addComponent(jLabel8)
                    .addComponent(CreateTorrent, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(URL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(partisi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(24, 24, 24)
                .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FileAsal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(GetName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fileTujuan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Rename))
                .addGap(18, 18, 18)
                .addComponent(CreateTorrent)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CreateTorrentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreateTorrentActionPerformed
        torrent = new Torrent();
        // Membuat torrent jika berhasil
        if ((FileAsal.getText() == null ? "" != null : !FileAsal.getText().equals(""))
                || (fileTujuan.getText() == null ? "" != null : !fileTujuan.getText().equals(""))
                || (URL.getText() == null ? "" != null : !URL.getText().equals(""))) // sudah terisi semua
        {
            try {
                try {
                    torrent.CreateTorrent(FileAsal.getText(), fileTujuan.getText(), Integer.parseInt(partisi.getSelectedItem().toString()) * 1000, URL.getText() + ":" + port.getText() + "/");
                } catch (UnsupportedEncodingException ex) {
                    Logger.getLogger(CreateTorrentForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Register File
            String parameterRequest = "register=" + torrent.fileName;
            String response = Request.sendGetRequest(torrent.announce, parameterRequest);

            // Add to file download
            addToFileDownload();

            JOptionPane.showMessageDialog(this, "Pembentukan Torrent sukses!");
            this.dispose();
            // Log
        } else {
            JOptionPane.showMessageDialog(this, "Ada field yang kosong");
        }
}//GEN-LAST:event_CreateTorrentActionPerformed

    private void RenameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RenameActionPerformed
        JFileChooser Save = new JFileChooser();
        /*Save.setFileFilter(new FileFilter() {

            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".torrent")
                        || f.isDirectory();
            }

            public String getDescription() {
                return "torrent files";
            }
        });*/
        Save.setCurrentDirectory(new File(""));
        int retval = Save.showSaveDialog(this);
        if (retval == JFileChooser.APPROVE_OPTION) {
            File F = Save.getSelectedFile();
            fileTujuan.setText(F.getAbsolutePath());
        }
}//GEN-LAST:event_RenameActionPerformed

    private void GetNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GetNameActionPerformed
        JFileChooser Open = new JFileChooser();
        Open.setCurrentDirectory(new File(""));
        int x = Open.showOpenDialog(this);
        if (x == JFileChooser.APPROVE_OPTION) {
            File F = Open.getSelectedFile();
            FileAsal.setText(F.getAbsolutePath());
        }
}//GEN-LAST:event_GetNameActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CreateTorrentForm dialog = new CreateTorrentForm(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CreateTorrent;
    private javax.swing.JTextField FileAsal;
    private javax.swing.JButton GetName;
    private javax.swing.JButton Rename;
    private javax.swing.JTextField URL;
    private javax.swing.JTextField fileTujuan;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JComboBox partisi;
    private javax.swing.JTextField port;
    // End of variables declaration//GEN-END:variables

    private void addToFileDownload() {
        FileDownloader file = new FileDownloader(torrent);

        // Set piece is available
        file.setAllAvail();

        // Add to global container
        Global.fileDownloads.add(file);
    }

}
